package com.amigo.online.provider;

import java.net.UnknownHostException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import com.mongodb.MongoClientURI;

@Configuration
public class MongoConfig {

    @Value("${spring.data.mongodb.video.uri}")
    private String mongoVideoUri;

    @Value("${spring.data.mongodb.user.uri}")
    private String mongoUserUri;

    @Value("${spring.data.mongodb.goods.uri}")
    private String mongoGoodsUri;

    @Value("${spring.data.mongodb.merchant.uri}")
    private String mongoMerchantUri;


    @Bean
    public MongoMappingContext mongoMappingContext() {
        MongoMappingContext mappingContext = new MongoMappingContext();
        return mappingContext;
    }

    @Bean
    @Primary
    public MongoDbFactory dbUserFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClientURI(mongoUserUri));
    }

    @Bean("userMongoTemplate")
    @Primary
    public MongoTemplate mongoUserTemplate() throws Exception {
        return new MongoTemplate(dbUserFactory());
    }

    @Bean
    public MongoDbFactory dbVideoFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClientURI(mongoVideoUri));
    }

    @Bean("videoMongoTemplate")
    public MongoTemplate mongoVideoTemplate() throws Exception {
        return new MongoTemplate(dbVideoFactory());
    }

    @Bean
    public MongoDbFactory dbGoodsFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClientURI(mongoGoodsUri));
    }

    @Bean("goodsMongoTemplate")
    public MongoTemplate mongoGoodsTemplate() throws Exception {
        return new MongoTemplate(dbGoodsFactory());
    }

    @Bean
    public MongoDbFactory dbMerchantFactory() throws UnknownHostException {
        return new SimpleMongoDbFactory(new MongoClientURI(mongoMerchantUri));
    }

    @Bean("merchantMongoTemplate")
    public MongoTemplate mongoMerchantTemplate() throws Exception {
        return new MongoTemplate(dbMerchantFactory());
    }
}
